<!--
 * @Author: xiaxia
 * @Description: 
 * @Date: 2022-11-10 10:58:32
 * @LastEditTime: 2024-05-30 17:02:34
 * @FilePath: \vue-admin-template\src\views\jsItem\ImgCompress\index.vue
-->
<template>
  <div class="app-container">
    <input type="file" accept="image/*" name="imageFile" @change="upload">
    <el-row :gutter="10">
      <el-col :span="12">
        <el-card>
          压缩前：
          <img id="test1" crossorigin alt="" width="100%">
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          压缩后：
          <img id="test" crossorigin alt=""  width="100%">
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
export default {
  name: 'ImgCompress',
  data () {
  return {
    dataUrl: ''
  }
  },
  components: {
  },
  created () {
  },
  methods: {
    upload () {
      let file = document.querySelector('input[type=file]').files[0] // 获取选择的文件，这里是图片类型
      console.log('压缩前的文件', file);
      let reader = new FileReader()
      reader.readAsDataURL(file) //读取文件并将文件以URL的形式保存在resulr属性中 base64格式
      reader.onload = (e) => { // 文件读取完成时触发
        let result = e.target.result // base64格式图片地址
        var image = new Image()
        image.src = result // 设置image的地址为base64的地址
        document.getElementById("test1").src = image.src
        image.onload = () => { // 图片加载完成后才能进行压缩处理，从而转换为base64 进行赋值
          let width = image.width // 图片宽度
          let height = image.height
          this.dataUrl = this.compress(image, width, height, 0.5)
          let file11 = this.dataURLtoFile(this.dataUrl, file.name)
          // console.log('base64', this.dataUrl);
          console.log('压缩后文件',file11);
          document.getElementById("test").src = this.dataUrl
        }
      }
    },
    /*
    * 图片压缩
    * img   原始图片
    * width  压缩后的宽度
    * height  压缩后的高度
    * ratio  压缩比率
    */
    compress (img, width, height, ratio) {
      let canvas, ctx, img64;
      canvas = document.createElement('canvas')
      canvas.width = width;
      canvas.height = height;
      ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, width, height);
      img64 = canvas.toDataURL("image/jpeg", ratio);
      return img64;
    },
    dataURLtoFile(dataurl, filename) {
      let arr = dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
      while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    }
  }
}
</script>

<style lang="less" scoped>
</style>
